<%@page language="java" contentType="text/html; charset=UTF-8" isELIgnored="false" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib prefix="html" tagdir="/WEB-INF/tags" %>
<!DOCTYPE html>
<html>
<html:header title="库存查询">

    <link rel="stylesheet" href="${baseUrl}css/public.css" media="all">
    <script src="${baseUrl}js/myEchart.js" charset="utf-8"></script>

    <style type="text/css">

    </style>

    <script>
        let option = {
            elem: '#selectHouse'
            ,placeholder:"全部"
            ,width:160
            , value: "0"
            ,clear:true
            , getChildren: function (value, callback) {
                var data = [];
                //表示是门店
                if (value == "0"){
                    get("${baseUrl}organization/store/getStores.action", function (res) {
                        if (res.code == 1){
                            data.push({value:"", label:"全部"});
                            $.each(res.data, function (i,d) {
                                data.push({value:d.id, label:d.name, hasChild:true});
                            });
                            callback(data);
                        }
                    });
                } else {
                    //表示是仓库
                    get("${baseUrl}organization/house/getHouseByStore.action?storeId="+value, function (res) {
                        if (res.code == 1){
                            data.push({value:"", label:"全部"});
                            $.each(res.data, function (i,d) {
                                data.push({value:d.id, label:d.name});
                            });

                            callback(data);
                        }
                    });
                }
            }
        };


        jQuery(function () {
            fixTableOperatorButton();
            ajaxSelect("${baseUrl}goods/type/getAll.action","goodsTypeId","全部");
            ajaxSelect("${baseUrl}organization/store/getStores.action","storeId","全部");

            getStockAmount();

            $("#export").click(function () {
                exportExcel();
            });
        });


        layui.use(['form', 'table','laydate','ajaxCascader','laytpl','element'], function () {
            let $ = layui.jquery,
                form = layui.form,
                table = layui.table,
                laydate = layui.laydate,
                element = layui.element,
                laytpl = layui.laytpl,
                cascader = layui.ajaxCascader,
                util = layui.util;

            laydate.render({
                elem: '#date',
                range:'~',
                done: function(value, date, endDate){
                    console.log(value); //得到日期生成的值，如：2017-08-18
                    console.log(date); //得到日期时间对象：{year: 2017, month: 8, date: 18, hours: 0, minutes: 0, seconds: 0}
                    console.log(endDate); //得结束的日期时间对象，开启范围选择（range: true）才会返回。对象成员同上。

                    $('[name="date1"]').val(getDateFromLayUiDate(date));
                    $('[name="date2"]').val(getDateFromLayUiDate(endDate));

                    table.reload('table',{where: genSearch(),page: {curr: 1}});
                    getStockAmount();
                    loadView();
                }
            });

            $(".view-button-group .layui-btn").click(function () {
                tabButtonClick(this);
                loadView();
            });

            renderTable();

            table.on('tool(table)', function (obj) {
                let houseId = $('[name="houseId"]').val();
                let storeId = $('[name="storeId"]').val();
                let data = obj.data;
                switch(obj.event){
                    case 'detail':
                        openTab("库存流水明细","${baseUrl}house/houseQueryDetail.action?goodsId="+data.id+"&storeId="+storeId+"&houseId="+houseId);
                        break;
                    case 'house':
                        openHouseStockDialog(data);
                        break;
                }
            });

            // Ajax传参模式
            cascader.load(option);

            // 选择器点击事件的监听
            cascader.on('click', '#selectHouse', function(data){
                let datas = cascader.getChooseData();
                $("[name='storeId']").val(datas[0]);
                $("[name='houseId']").val(datas[1]);
                getStockAmount();
                loadView();
            });

            $(".cascader-clear").click(function () {
                $("[name='houseId']").val("");
                $("[name='storeId']").val("");
                getStockAmount();
                loadView();
            });


            form.on('select(goodsTypeId)', function (data) {
                table.reload('table',{where: genSearch(),page: {curr: 1}});
            });

            form.on('checkbox(filterZero)', function (data) {
                table.reload('table',{where: genSearch(),page: {curr: 1}});
            });

            form.on('checkbox(goodsStatus)', function (data) {
                table.reload('table',{where: genSearch(),page: {curr: 1}});
            });

            form.on('submit(search)', function (data) {
                table.reload('table',{where: genSearch(),page: {curr: 1}});
                return false;
            });




            function loadTableView() {
                table.reload('table',{where: genSearch(),page: {curr: 1}});
            }

            function loadView(){
                var viewId = $(".view-button-group .layui-this").attr("view-id");

                if (viewId.indexOf("table") != -1) {
                    loadTableView();
                } else {
                    loadChartView();
                }
            }
        });

        function exportExcel() {
            confirm("是否导出选择的数据?",function () {
                tipLoad("处理中，请稍后");
                post("${baseUrl}house/houseQuery/export.action" + genParam(genSearch()),{},function (resp) {
                    closeAll();
                    if (resp.code == 1) {
                        downloadFileByForm("${baseUrl}file/excel/temp/"+resp.data);
                    }  else {
                        tip(resp.msg);
                    }
                });
            });

        }

        function genSearch() {
            let json = getFormJson($("#searchForm"));
            json.goodsStatus = $('[name="goodsStatus"]').next().hasClass("layui-form-checked") ? 1:'';
            json.filterZero = $('[name="filterZero"]').next().hasClass("layui-form-checked") ? true:'';
            return json;
        }

        function getStockAmount() {
            let houseId = $('[name="houseId"]').val();
            let storeId = $('[name="storeId"]').val();
            get("${baseUrl}goodsStock/getTotalStockAmount.action?storeId="+storeId+"&houseId="+houseId, function (res) {
                if (res.code == 1) {
                    $("#totalStockAmount").html(getPrice(res.data));
                }
            });

            get("${baseUrl}goodsStock/getHighestStockAmountWithGoods.action?storeId="+storeId+"&houseId="+houseId, function (res) {
                if (res.code == 1) {
                    $("#highestGoods").html(res.data.highestGoods);
                    $("#highestStockAmount").html(getPrice(res.data.highestStockAmount));
                }
            });
        }

        function renderTable() {
            layui.table.render({
                id:'table',
                elem: '#table',
                url: "${baseUrl}house/houseQuery/getList.action",
                where : genSearch(),
                cols: [[
                    {width:70,title:"序号",templet:function (d) {
                            return genTableIndex(d.status==2, "停用", d);
                        }},
                    {field: 'no', width: 130, title: '商品编号',style:"font-size:12px;"},
                    {field: 'name',width: 120, title: '商品名称',style:"font-size:12px;"},
                    {field: 'norms',width: 120, title: '规格',style:"font-size:12px;"},
                    {width: 120, title: '属性',style:"font-size:12px;",templet: function(d){
                            return genAttr(d.attrNameVoList);
                        }},
                    {width: 80, title: '单位',style:"font-size:12px;",templet: function(d){
                            return d.goodsUnitVoList[0].unit.name;
                        }},
                    {width: 120, title: '初期库存',style:"font-size:12px;",templet: function (d) {
                            let initStock = 0;
                            $.each(d.goodsInitList, function (i,item) {
                                initStock += item.initNum;
                            });
                            return getNumber(initStock);
                        }},
                    {width: 90, title: '库存',style:"font-size:12px;",templet: function (d) {
                        let stock = 0;
                        $.each(d.goodsStockVoList, function (i,item) {
                            stock += item.num;
                        });
                        return getNumber(stock);
                    }},
                    {width: 90, title: '成本价',style:"font-size:12px;",templet: function (d) {
                            return getPrice(d.cost);
                        }},
                    {width: 90, title: '库存总额',style:"font-size:12px;",templet: function (d) {
                        let stock = 0;
                        $.each(d.goodsStockVoList, function (i,item) {
                            stock += item.num;
                        });
                        return getPrice(d.cost*stock);
                    }},
                    {title: '操作', minWidth: 80,fixed:'right', templet: '#operBar'},
                ]],
                limit: 10,
                page: { //支持传入 laypage 组件的所有参数（某些参数除外，如：jump/elem） - 详见文档
                    layout: ['limit', 'count', 'prev', 'page', 'next', 'skip'] //自定义分页布局
                    //,curr: 5 //设定初始在第 5 页
                    ,groups: 5 //只显示 5 个连续页码
                    ,first: false //不显示首页
                    ,last: false //不显示尾页
                },
                done: function(res, curr, count){
                    setTableLineCss("table",res.data, "status", 2, "font-gray-c2c2c2");
                }

            });
        }

        function openHouseStockDialog(data) {
            layui.use(['laytpl'], function () {
                let $ = layui.jquery,
                    laytpl = layui.laytpl,
                    util = layui.util;

                let area;
                if (document.documentElement.clientWidth > 600){
                    area = ['550px', (document.documentElement.clientHeight-40)+'px'];
                } else {
                    area = [(document.documentElement.clientWidth-8)+'px', (document.documentElement.clientHeight-8)+'px'];
                }
                area='550px';

                let houseId = $('[name="houseId"]').val();
                let storeId = $('[name="storeId"]').val();

                get("${baseUrl}goodsStock/getGoodsStockGroupByHouse.action?storeId="+storeId+"&houseId="+houseId+"&goodsId="+data.id, function (res) {
                    if (res.code == 1) {
                        var getTpl = stockByHouseBar.innerHTML;
                        laytpl(getTpl).render(res.data, function(html){
                            let index = layer.open({
                                title:'库存分布',
                                area: area,
                                skin: 'layui-layer-molv',
                                type: 1,
                                content: html,
                                btn: ['关闭'],
                                yes: function(index, layero){
                                    closeDialog(index);
                                },
                            });
                        });

                    } else {
                        errTip(res.msg);
                    }
                });
            });
        }
    </script>

</html:header>
<body>
<div class="layuimini-container">
    <div class="layuimini-main">
        <form class="layui-form" action="" id="searchForm">
            <input type="hidden" name="houseId">
            <input type="hidden" name="storeId">
            <input type="hidden" name="date1">
            <input type="hidden" name="date2">

            <div class="layui-form-item">
                <div class="layui-inline">
                    <label class="layui-form-label">门店仓库</label>
                    <div class="layui-input-inline">
                        <cascader id="selectHouse"></cascader>
                    </div>
                </div>

                <div class="layui-inline">
                    <label class="layui-form-label"></label>
                    <div class="layui-input-inline">
                        <div class="layui-btn-group view-button-group">
                            <a view-id="table-div" view-class="view-div" class="layui-btn layui-btn-normal fontWhite layui-this">列表视图</a>
                            <a view-id="chat-div" view-class="view-div" class="layui-btn layui-btn-primary fontBlue">图表视图</a>
                        </div>
                    </div>
                </div>
            </div>

            <div style="background: #f2f2f2;padding: 0 10px;margin: 10px -10px 0px -10px;border-top: #dddddd solid 1px;border-bottom: #dddddd solid 1px;overflow: hidden;">
                <div style="float: left;width: 300px;height: 60px;line-height: 60px;">
                    <span style="color: #666">库存总额:</span>
                    <span style="color: #FF5722;font-size: 14px;">￥</span>
                    <span id="totalStockAmount" style="text-align: right;color: #FF5722;font-size: 20px;font-weight: bold;"></span>
                </div>

                <div style="float: left;min-width: 300px;height: 60px;line-height: 60px;">
                    <span style="color: #666">库存总额最高商品:</span>
                    <span id="highestGoods" style="font-weight:bold;color: #666"></span>
                    <span style="color: #FF5722;font-size: 14px;">￥</span>
                    <span id="highestStockAmount" style="color: #FF5722;font-size: 20px;"></span>
                </div>
            </div>



            <div id="chat-div" class="view-div w100" style="display: none">
                <div class="layui-card">
                    <div class="layui-card-header">
                        库存排行
                    </div>
                    <div class="layui-card-body">
                        <div class="layui-inline">
                            <div class="layui-btn-group chat-rank-button-group">
                                <a class="layui-btn layui-btn-normal fontWhite layui-this goods">按商品</a>
                                <a class="layui-btn layui-btn-primary fontBlue store">按门店</a>
                                <a class="layui-btn layui-btn-primary fontBlue house">按仓库</a>
                            </div>
                        </div>

                        <div id="chat-rank" class="h300"></div>

                        <div class="h300 lh300 font20 fontB fontC_ccc" style="text-align: center;display: none;">
                            统计值为0或负数无法统计
                        </div>
                    </div>
                </div>

                <div class="layui-card">
                    <div class="layui-card-header">
                        库存比重
                    </div>
                    <div class="layui-card-body">
                        <div class="layui-inline">
                            <div class="layui-btn-group chat-ratio-button-group">
                                <a class="layui-btn layui-btn-normal fontWhite layui-this goods">按商品</a>
                                <a class="layui-btn layui-btn-primary fontBlue store">按门店</a>
                                <a class="layui-btn layui-btn-primary fontBlue house">按仓库</a>
                            </div>
                        </div>

                        <div id="chat-ratio" class="h300"></div>

                        <div class="h300 lh300 font20 fontB fontC_ccc" style="text-align: center;display: none;">
                            统计值为0或负数无法统计
                        </div>
                    </div>
                </div>

                <script>
                    function loadChartView(){

                        layui.use(['form', 'echarts'], function () {
                            let $ = layui.jquery,
                                form = layui.form,
                                echarts = layui.echarts;
                            window.chat_rank_chat = echarts.init(document.getElementById('chat-rank'),'walden');
                            window.chat_ratio_chat = echarts.init(document.getElementById('chat-ratio'),'walden');

                            window.onresize = function(){
                                window.chat_ratio_chat.resize();
                                window.chat_rank_chat.resize();
                            };

                            loadRatioChart();
                            loadRankChart();

                            $(".chat-rank-button-group .layui-btn").click(function () {
                                tabButtonClick(this);
                                loadRankChart();
                            });

                            $(".chat-ratio-button-group .layui-btn").click(function () {
                                tabButtonClick(this);
                                loadRatioChart();
                            });

                            function loadRankChart() {
                                let url;
                                if ($(".chat-rank-button-group").find(".layui-this").hasClass("goods")) {
                                    url = "${baseUrl}goodsStock/getAmountOrderByGoods.action"+genParam(getFormJson($("#searchForm")))+ "&filterZero=true";
                                } else if ($(".chat-rank-button-group").find(".layui-this").hasClass("store")) {
                                    url = "${baseUrl}goodsStock/getAmountOrderByStore.action"+genParam(getFormJson($("#searchForm")))+ "&filterZero=true";
                                } else if ($(".chat-rank-button-group").find(".layui-this").hasClass("house")) {
                                    url = "${baseUrl}goodsStock/getAmountOrderByHouse.action"+genParam(getFormJson($("#searchForm")))+ "&filterZero=true";
                                }
                                get(url, function (res) {
                                    if (!emptyList(res.data)) {
                                        $("#chat-rank").css("display","block");
                                        $("#chat-rank").next().css("display","none");
                                        window.chat_rank_chat.setOption(genChatRankOption(genChatRankData("库存","amount",res.data)));
                                    } else {
                                        $("#chat-rank").css("display","none");
                                        $("#chat-rank").next().css("display","block");
                                    }
                                });
                            }

                            function loadRatioChart() {
                                let url;
                                if ($(".chat-ratio-button-group").find(".layui-this").hasClass("goods")) {
                                    url = "${baseUrl}goodsStock/getAmountOrderByGoods.action"+genParam(getFormJson($("#searchForm")))+ "&filterZero=true";
                                } else if ($(".chat-ratio-button-group").find(".layui-this").hasClass("store")) {
                                    url = "${baseUrl}goodsStock/getAmountOrderByStore.action.action"+genParam(getFormJson($("#searchForm")))+ "&filterZero=true";
                                } else if ($(".chat-ratio-button-group").find(".layui-this").hasClass("house")) {
                                    url = "${baseUrl}goodsStock/getAmountOrderByHouse.action"+genParam(getFormJson($("#searchForm")))+ "&filterZero=true";
                                }

                                get(url, function (res) {
                                    if (!emptyList(res.data)) {
                                        $("#chat-ratio").css("display","block");
                                        $("#chat-ratio").next().css("display","none");
                                        window.chat_ratio_chat.setOption(genChatRatioOption(genChatRatioData("库存","amount",res.data)));
                                    } else {
                                        $("#chat-ratio").css("display","none");
                                        $("#chat-ratio").next().css("display","block");
                                    }
                                });
                            }
                        });
                    }
                </script>
            </div>

            <div id="table-div" class="view-div w100 mt10">
                <div class="layui-inline mb4">
                    <div class="label">不显示停用</div>
                    <div style="display: inline-block;width: 30px;">
                        <input type="checkbox" name="goodsStatus"  title="" lay-skin="primary" value="true" lay-filter="goodsStatus">
                    </div>
                </div>

                <div class="layui-inline mb4">
                    <div class="label">过滤零库存</div>
                    <div style="display: inline-block;width: 30px;">
                        <input type="checkbox" name="filterZero"  title="" lay-skin="primary" value="true" lay-filter="filterZero">
                    </div>
                </div>

                <div class="layui-inline mb4">
                    <div class="label">商品分类</div>
                    <div style="display: inline-block;width: 160px;">
                        <select name="goodsTypeId" lay-filter="goodsTypeId"></select>
                    </div>
                </div>

                <div class="layui-inline mb4">
                    <div class="label">搜索信息</div>
                    <div style="display: inline-block;width: 160px;">
                        <input type="text" id="search" name="search" style="font-size: 12px;" placeholder="编号、名称、规格、属性、条形码" class="layui-input">
                    </div>
                </div>

                <div class="layui-inline mb4">
                    <div class="layui-btn-group">
                        <a class="layui-btn " lay-submit="" lay-filter="search" id="btn-search"><i class="layui-icon layui-icon-search"></i></a>
                        <a class="layui-btn layui-btn-primary" id="export">导出</a>
                    </div>
                </div>

                <table class="layui-hide" id="table" lay-filter="table" lay-size="sm"></table>
            </div>
            </form>
    </div>
</div>
</body>

<script type="text/html" id="operBar">
    <a class="layui-btn layui-btn-xs layui-btn-normal " lay-event="detail">详情</a>
    <a class="layui-btn layui-btn-xs layui-btn-warm " lay-event="house">库存分布</a>
</script>

<script type="text/html" id="stockByHouseBar">
    <table class="layui-table" style="margin: 0">
        <thead>
        <tr>
            <th>序号</th>
            <th>门店</th>
            <th>仓库</th>
            <th>当前库存</th>
        </tr>
        </thead>

        <tbody>
        {{#  layui.each(d, function(index, item){ }}
        <tr>
            {{# if(item.houseStatus == 2) { }}
                <td><span class="layui-badge layui-bg-gray">停用</span></td>
                <td style="font-size: 12px;color: #c2c2c2;">{{ item.storeName }}</td>
                <td style="font-size: 12px;color: #c2c2c2;">{{ item.houseName }}</td>
                <td style="color: #c2c2c2;">{{ item.stock }}</td>
            {{# } else { }}
                <td>{{ (index+1) }}</td>
                <td style="font-size: 12px;">{{ item.storeName }}</td>
                <td style="font-size: 12px;">{{ item.houseName }}</td>
                <td>{{ item.stock }}</td>
            {{# } }}
        </tr>
        {{#  }); }}
        </tbody>
    </table>
</script>

<html:loading/>
</html>